<?php

namespace app\controllers;
use Yii;
use yii\web\Controller;
use Faker\Provider\Uuid;


class TrainingController extends Controller{
    public $enableCsrfValidation = false;
    public function init()
    {
        parent::init();
        header('Access-Control-Allow-Origin: *');
    }
    public function actionMyCourseTraining(){
        $userid = $_REQUEST['userid'];
//        $sql="select i.id,i.name from t_course_member m left join t_course_info i on i.id=m.course_id where m.user_id=:uid and m.del_flag=0 and i.del_flag=0";
//        $data = \Yii::$app->db->createCommand($sql)->bindValue(':uid', $userid)->queryAll();
        
        $sql="SELECT
	i.id,
	i.name,count(q.id) as num,t.train 
FROM
	t_course_member m
	LEFT JOIN t_course_info i ON i.id = m.course_id
	LEFT JOIN t_quiz_course_ques_relation q ON q.course_id = i.b_course_info_id 
	left join t_quiz_question qq on qq.id = q.question_id 
	left join (select count(id) as train,t_course_id from t_quiz_student_ques_exercise where create_by=:uid and del_flag=0 group by t_course_id) t on t.t_course_id = i.id 
WHERE
	m.user_id = :uid 
	AND m.del_flag = 0 
	AND i.del_flag =0 and q.del_flag=0 and qq.type in ( 'questionType.yesOrNo', 'questionType.singleChoice', 'questionType.moreChoice') group by i.id";
        
        $data = Yii::$app->db->createCommand($sql)->bindValue(':uid', $userid)->queryAll();
        $result = [
            'msg' => '查找成功',
            'ver' => '1.5.0',
            'data' => $data,
            'success' => true,
            'code' => '200'
        ];
        Yii::$app->end(json_encode($result));
    }
    
    public function actionDoTraining(){
        $courseid = $_REQUEST['courseid'];
        $userid = $_REQUEST['userid'];
        $start    = $_REQUEST['start'];
        $sql="select qq.*,d.name from t_course_info i 
                LEFT JOIN t_quiz_course_ques_relation q ON q.course_id = i.b_course_info_id 
                left join t_quiz_question qq on qq.id = q.question_id 
                left join (select value,name from t_sys_dictionary where type='questionType') d on d.value= qq.type
                where i.id=:courseid and qq.type in ( 'questionType.yesOrNo', 'questionType.singleChoice', 'questionType.moreChoice') and qq.del_flag=0 
                order by qq.create_time asc limit ".$start.",1";
        $question = \Yii::$app->db->createCommand($sql)->bindValues([':courseid'=>$courseid])->queryOne();
        $sql="select * from t_quiz_question_answer where ques_id=:qid and del_flag=0 order by answ_code asc";
        $answers = \Yii::$app->db->createCommand($sql)->bindValue(':qid', $question['id'])->queryAll();
        
        $sql="select answer from t_quiz_student_ques_exercise where create_by=:uid and del_flag=0 and t_course_id=:cid and ques_id=:qid";
        $myanswer = \Yii::$app->db->createCommand($sql)->bindValues([':uid'=>$userid,':cid'=>$courseid,':qid'=>$question['id']])->queryScalar();
        $result = [
            'msg' => '查找成功',
            'ver' => '1.5.0',
            'data' => array_merge($question,array('answers'=>$answers),array('myanser'=>$myanswer)),
            'success' => true,
            'code' => '200'
        ];
        Yii::$app->end(json_encode($result));
    }
    
    public function actionSaveQuestionAnswer(){
        $tcourseId = $_REQUEST['course_id'];
        $userId =$_REQUEST['user_id'];
        $ques_id = $_REQUEST['question_id'];
        $bcourseId = \app\models\TCourseInfo::findOne($tcourseId)['b_course_info_id'];
        $projectId = '31';
        $answerContent = isset($_REQUEST['answerContent'])?$_REQUEST['answerContent']:"";
        $a=explode(',', trim($answerContent,','));
        sort($a);
        $answerContent = implode(',',$a);
//        //获取问题类型
//        $question = \app\models\TQuizQuestion::findOne($ques_id);
        //查询这个题目下的所有正确答案
        $sql="SELECT answ_code from t_quiz_question_answer where ques_id=:ques_id and is_right='yesOrNo.yes' order by answ_code asc";
        $questionAnswerYes = \Yii::$app->db->createCommand($sql)->bindValue(':ques_id', $ques_id)->queryColumn();
        $questionAnswerYesStr = implode(',', $questionAnswerYes);
        //查询答题卡里面是否存储这条答案
        $resultAnswer = \app\models\TQuizStudentQuesExercise::find()->where(':t_course_id=:t_course_id and del_flag=:d and ques_id=:ques_id and create_by=:userId',[':t_course_id'=>$tcourseId,':d'=>0,':ques_id'=>$ques_id,':userId'=>$userId])->one();
        if(empty($resultAnswer)){
            $resultAnswer = new \app\models\TQuizStudentQuesExercise();
            $resultAnswer->id = \Faker\Provider\Uuid::uuid();
            $resultAnswer->b_course_id = $bcourseId;
            $resultAnswer->t_course_id = $tcourseId;
            $resultAnswer->ques_id = $ques_id; 
            $resultAnswer->answer = $answerContent;
            $resultAnswer->is_correct = $questionAnswerYesStr==$answerContent?'yesOrNo.yes':'yesOrNo.no';
            if($resultAnswer->is_correct=='yesOrNo.yes'){//答案错误的不填写分数，新增加学生填写答案里的正确答案
                $resultAnswer->points_awarded = 1;
                $resultAnswer->answer_right = $questionAnswerYesStr;
            }else{
                $resultAnswer->points_awarded = '';
            }
            $resultAnswer->answer_time = date('Y-m-d H:i:s');
            $resultAnswer->create_by = $userId;
            $resultAnswer->create_time = date('Y-m-d H:i:s');
            $resultAnswer->del_flag = 0;      
            $resultAnswerRes = $resultAnswer->save();
            if($resultAnswerRes != false){
                $resultAnswerFlag = TRUE;
            }else{
                $resultAnswerFlag = false;
            }
        }else{
            $resultAnswer->answer = $answerContent;
            $resultAnswer->is_correct = $questionAnswerYesStr==$answerContent?'yesOrNo.yes':'yesOrNo.no';
            if($resultAnswer->is_correct=='yesOrNo.yes'){//答案错误的不填写分数，新增加学生填写答案里的正确答案
                $resultAnswer->points_awarded = 1;
                $resultAnswer->answer_right = $questionAnswerYesStr;
            }else{
                $resultAnswer->points_awarded = '';
            }
            $resultAnswer->update_by = $userId;
            $resultAnswer->update_time = date('Y-m-d H:i:s');
            $resultAnswerRes = $resultAnswer->save();
            if($resultAnswerRes != false){
                $resultAnswerFlag = TRUE;
            }else{
                $resultAnswerFlag = false;
            }
        }
        if($resultAnswerFlag){
            $result = [
                'msg' => '保存成功',
                'ver' => '1.5.0',
                'data' => [],
                'success' => true,
                'code' => '200'
            ];
        }else{
            $result = [
                'msg' => '保存失败',
                'ver' => '1.5.0',
                'data' => [],
                'success' => true,
                'code' => '500'
            ];
        }
        Yii::$app->end(json_encode($result));
    }
}

